const state = {
  // 购物车的数组，用来存储购物车中每个商品的信息对象
  // 每个商品的信息对象，都包含如下 6 个属性：
  // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
  cart: [],
};
const mutations = {
  // 添加到购物车
  addToCart(state, goods) {
    // 根据提交的商品的Id，查询购物车中是否存在这件商品
    const res = state.cart.findIndex(
      (item) => item.goods_id === goods.goods_id
    );
    console.log(res);
    if (res === -1) {
      // 如果购物车中没有这件商品，则直接 push
      state.cart.push(goods);
    } else {
      // 如果购物车中有这件商品，则只更新数量即可
      state.cart[res].goods_count++;
    }
  },
  // 修改勾选状态
  updateGoodsState(state, goods) {
    const res = state.cart.find((item) => item.goods_id === goods.goods_id);

    if (res) {
      res.goods_state = goods.goods_state;
    }
  },
  // 修改物品数量
  updateGoodsNum(state, goods) {
    const res = state.cart.find((item) => item.goods_id === goods.goods_id);

    if (res) {
      res.goods_count = goods.goods_count;
    }
  },
  // 删除商品
  delGoods(state, goods) {
    const index = state.cart.findIndex(
      (item) => item.goods_id === goods.goods_id
    );
    if (index !== -1) {
      state.cart.splice(index, 1);
    }
  },
};

const actions = {};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
